package com.atguigu.petstore.app.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.petstore.feign.member.MemberFeignClient;
import com.atguigu.petstore.app.service.LoginService;
import com.atguigu.petstore.app.vo.LoginParamVo;
import com.atguigu.petstore.common.constant.RedisConst;
import com.atguigu.petstore.common.execption.AppPetStoreException;
import com.atguigu.petstore.common.result.Result;
import com.atguigu.petstore.common.result.ResultCodeEnum;
import com.atguigu.petstore.member.entity.MemberInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author lfy
 * @Description
 * @create 2023-09-27 14:11
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignClient memberFeignClient;

    @Override
    public String login(LoginParamVo param) {
        //1、验证前端带来的验证码是否正确
        String code = redisTemplate.opsForValue().get(RedisConst.PHONE_CODE + param.getPhone());
        if(!param.getCode().equals(code)){
            //同一个验证码被多次请求带了，也只处理一次
            throw new AppPetStoreException(ResultCodeEnum.APP_CODE_INVAILD);
        }

        //2、验证码是一个一次性令牌，用完就删除
        redisTemplate.delete(RedisConst.PHONE_CODE + param.getPhone());


        MemberInfo redisLoginUser = new MemberInfo();

        //3、如果用户已经注册过。直接查询出信息，登录成功
        Result<MemberInfo> memeber = memberFeignClient.getMemeberByPhone(param.getPhone());

        MemberInfo memeberData = memeber.getData();

        if(memeberData == null){
            //远程没有查询到会员信息
            Result<MemberInfo> register = memberFeignClient.register(param.getPhone());
            redisLoginUser = register.getData();
            log.info("会员：{} 第一次登录，自动注册完成",param.getPhone());
        }else {
            //用户有就是登录成功
            redisLoginUser = memeberData;
        }

        //4、生成一个唯一令牌，并保存用户信息；  login:member:令牌 = MemberInfo的json
        String token = UUID.randomUUID().toString().replace("-", "");

        redisTemplate.opsForValue()
                .set(RedisConst.MEMBER_LOGIN_KEY+token, JSON.toJSONString(redisLoginUser),7, TimeUnit.DAYS);




        return token;
    }

    @Override
    public MemberInfo getUserInfo(String token) {
        String json = redisTemplate.opsForValue().get(RedisConst.MEMBER_LOGIN_KEY + token);
        if(!StringUtils.hasText(json)){
            throw new AppPetStoreException(ResultCodeEnum.APP_MEMBER_INVAILD);
        }
        MemberInfo info = JSON.parseObject(json, MemberInfo.class);
        return info;
    }
}
